package com.javaspeak.concurrency.synchronizedperformance.contended;

import java.util.concurrent.Callable;

/**
 * Calls the incrementAndGet method several times of the Disruptor's Sequence
 * 
 * @author John Dickerson
 */
public class CallableCallingDisruptorSequenceMethod implements Callable<int[]> {

    private int numberCounterIncrementsPerThread;
    private ContendedCounter contendedCounter;
    private int[] increments;
    
    
    public CallableCallingDisruptorSequenceMethod( 
            int numberCounterIncrementsPerThread, 
                ContendedCounter contendedCounter, int sizeArrayReturned ){
     
        this.numberCounterIncrementsPerThread = numberCounterIncrementsPerThread;
        this.contendedCounter = contendedCounter;
        increments = new int[ sizeArrayReturned ];
        
        for ( int i=0; i<sizeArrayReturned; i++ ){
            
            increments[ i ] = -1;
        }
    }
    
    
    /**
     * @return the increments
     */
    public int[] getIncrements() {
    
        return increments;
    }
    
    
    /* (non-Javadoc)
     * @see java.util.concurrent.Callable#call()
     */
    @Override
    public int[] call() throws Exception {
        
        try {
            int increment;
            
            for ( int i=0; i<numberCounterIncrementsPerThread; i++ ){
                
                increment = 
                     contendedCounter.incrementSequenceFromDisruptor();
                
                increments[ increment ] = increment;
            }
            
            return increments;
        }
        catch( Exception e ){
            
            throw e;
        }
    }
}    
